package org.lzy.shop.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.viewmodel.repository.PayRepository
import org.lzy.shop.viewmodel.repository.lmpl.PayRepositoryImpl

/**
 * 支付的VM层
 */
class PayModel() : BaseViewModel(){

    private val payRepository: PayRepository = PayRepositoryImpl()

    val payData = MutableLiveData<String?>()

    /**
     * 支付方法
     * @param orderId 订单ID
     * @param payType 支付类型，默认值为1（支付宝）
     */
    fun pay(orderId: Int, payType: Int = 1): LiveData<String?> {
        viewModelScope.launch {
            try {
                val response = withTimeout(15000) {
                    payRepository.pay(orderId, payType)
                }

                if (response != null) {
                    payData.value = response
                } else {
                    errorMessage.value = "支付失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "支付异常"
            }
        }
        return payData
    }
}